package com.zys.service.impl;

import java.util.*;

import com.zys.pojo.Role;
import com.zys.dao.RoleDao;
import com.zys.dao.RightDao;
import com.zys.service.RoleService;
import com.zys.utils.SerializeUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

  @Autowired
  private RoleDao roleDao;

  @Autowired
  private RightDao rightDao;

  @Autowired
  private JedisPool jedisPool;

  @Override
  public List<Role> findAll() throws Exception {
    Jedis jedis = jedisPool.getResource();
    byte[] bytes = jedis.hget("roleList".getBytes(), "roleList".getBytes());

    // 判断 redis 是否有该有数据
    if (bytes != null && bytes.length > 0) {
      return (ArrayList<Role>) SerializeUtils.deserialize(bytes);
    }

    List<Role> roleList = roleDao.findAll();

    jedis.hset("roleList".getBytes(), "roleList".getBytes(), SerializeUtils.serialize(roleList));
    return roleList;
  }

  @Override
  public void add(Integer[] rightsId, Role role) {
    roleDao.add(role);
    Integer roleId = role.getId();
    for (Integer rightId : rightsId) {
      Map<String, Integer> map = new HashMap<>();
      map.put("roleId", roleId);
      map.put("rightId", rightId);
      roleDao.setRoleIdAndRightId(map);
    }
    // 从 redis 中移除
    jedisPool.getResource().hdel("roleList".getBytes());
  }

  @Override
  public Role findRoleById(Integer id) {
    Role role = roleDao.findRoleById(id);
    role.setRights(rightDao.findRightsByRoleId(id));
    return role;
  }

  @Override
  public void edit(Role role) {
    roleDao.edit(role);
    jedisPool.getResource().hdel("roleList".getBytes());
  }

  @Override
  public List<Integer> findRightsIdsByRoleId(Integer id) {
    return roleDao.findRightsIdsByRoleId(id);
  }

  @Override
  public void setDistribution(Integer id, Integer[] rightsId) {
    roleDao.rmRelation4RoleAndRights(id);
    for (Integer rid : rightsId) {
      setRelation4RoleAndRights(id, rid);
    }
  }

  @Override
  public void delete(Integer id) {
    roleDao.rmRelation4RoleAndRights(id);
    roleDao.delete(id);
    jedisPool.getResource().hdel("roleList".getBytes());
  }

  private void setRelation4RoleAndRights(Integer roleId, Integer rightsId) {
    Map<String, Integer> map = new HashMap<>();
    map.put("roleId", roleId);
    map.put("rightsId", rightsId);
    roleDao.setRelation4RoleAndRights(map);
  }
}
